﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Data.Odbc;

namespace WLMCoreLibrary
{
    /// <summary>
    /// Es el usuario que esta logeado actualmente en el sistema
    /// </summary>
    public class CurrentUser
    {
        public static void Clear()
        {
            Email = null;
            NivelUsuario = 0;
            IdUsuario = 0;
            UserName = null;
            LogOutUser();
        }
        
        public static string Email
        {
            get { return HttpContext.Current.Session["userEmail"] as string; }
            set { HttpContext.Current.Session["userEmail"] = value; }
        }

        public static string UserName
        {
            get
            {
                if (HttpContext.Current.Session["UserName"] != null)
                    return HttpContext.Current.Session["UserName"] as string;
                else
                    return "Invitado";
            }
            set
            {
                HttpContext.Current.Session["UserName"] = value;
            }
        }

        /// <summary>
        /// Identificador Unico de Usuario dentro del sistema
        /// </summary>
        public static int IdUsuario
        {
            get
            {
                if (HttpContext.Current.Session["idUsuario"] != null)
                    return Convert.ToInt32(HttpContext.Current.Session["idUsuario"]);

                else
                    return 0;
            }
            set
            {
                HttpContext.Current.Session["idUsuario"] = value;
            }
        }


        /// <summary>
        /// Nivel de Autorizacion de el usuario dentro del sistema
        /// </summary>
        public static int NivelUsuario
        {
            get
            {
                if (HttpContext.Current.Session["nivelUsuario"] != null)
                    return Convert.ToInt32(HttpContext.Current.Session["nivelUsuario"]);

                else
                    return 0;
            }
            set
            {
                HttpContext.Current.Session["nivelUsuario"] = value;
            }
        }

       
        public static void LogOnUser(MiWebSiteUser usuario)
        {
            IdUsuario = usuario.id;
            UserName = usuario.username;
            NivelUsuario = usuario.nivelUsuario;
            Email = usuario.email;
            usuario.ultimoLogin = DateTime.Now;
            usuario.Save();
        }
        public static void LogOnUser(MiWebSiteUser usuario, bool recordar)
        {
            LogOnUser(usuario);
            if (recordar)
            {
                HttpCookie cookieUsuario = new HttpCookie("usuario", usuario.username);
                cookieUsuario.Expires = DateTime.Now.AddMonths(1);
                HttpCookie cookiePassword = new HttpCookie("password", usuario.password);
                cookiePassword.Expires = DateTime.Now.AddMonths(1);
                HttpCookie cookieRecordar = new HttpCookie("recordarme", "true");
                cookieRecordar.Expires = DateTime.Now.AddMonths(1);
                cookiePassword.Domain = "." + CurrentDomain.DomainName;
                cookieRecordar.Domain = "." + CurrentDomain.DomainName;
                cookieUsuario.Domain = "." + CurrentDomain.DomainName;
                HttpContext.Current.Response.Cookies.Add(cookieUsuario);
                HttpContext.Current.Response.Cookies.Add(cookiePassword);
                HttpContext.Current.Response.Cookies.Add(cookieRecordar);
            }
        }
        public static void LogOutUser()
        {
            IdUsuario = 0;
            NivelUsuario = 0;
            Email = "";
            UserName = "";
            HttpContext.Current.Response.Cookies.Clear();
            HttpContext.Current.Request.Cookies.Clear();
            HttpCookie cookieUsuario = new HttpCookie("usuario");
            cookieUsuario.Expires = DateTime.Now.AddDays(-1d);
            cookieUsuario.Domain = "." + CurrentDomain.DomainName;
            HttpContext.Current.Response.Cookies.Add(cookieUsuario);
            HttpCookie cookiePassword = new HttpCookie("password");
            cookiePassword.Expires = DateTime.Now.AddDays(-1d);

            cookiePassword.Domain = "." + CurrentDomain.DomainName;
            HttpContext.Current.Response.Cookies.Add(cookiePassword);
            HttpCookie cookieRecordar = new HttpCookie("recordarme");
            cookieRecordar.Expires = DateTime.Now.AddDays(-1d);

            cookieRecordar.Domain = "." + CurrentDomain.DomainName;
            HttpContext.Current.Response.Cookies.Add(cookieRecordar);

            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Session.Clear();


        }
    }

    /// <summary>
    /// Dominio actual en el que se encuentra el navegador de internet
    /// </summary>
    public class CurrentDomain
    {
        public static string DomainName
        {
            get
            {
                if (HttpContext.Current.Session["dominio"] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Session["dominio"].ToString();

            }
        }

        public static string Ciudad
        {
            get
            {
                if (HttpContext.Current.Session["ciudad"] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Session["ciudad"].ToString();

            }
        }


        public static string SubDomain
        {
            get
            {

                if (HttpContext.Current.Session["dominio"] == null)
                    GetDeCurrentDomainInfo();
                string _subdomain;
                string[] subDomSeparator = { HttpContext.Current.Session["dominio"].ToString() };
                string _host = HttpContext.Current.Request.Url.Host;
                _subdomain = _host.Split(subDomSeparator, StringSplitOptions.None)[0].Replace(".", "");
                if (_subdomain == "")
                    _subdomain = "www";
                return _subdomain;

            }
        }

        public static int IdentificadorDominio
        {
            get
            {
                if (HttpContext.Current.Session["idDominio"] == null)
                    GetDeCurrentDomainInfo();
                return Convert.ToInt32(HttpContext.Current.Session["idDominio"]);
            }
        }

        private static void GetDeCurrentDomainInfo()
        {
            dbConnector ConexionDB = new dbConnector();
            string _host;
            _host = HttpContext.Current.Request.Url.Host;
            char[] subDomSeparator = { '.' };
            string _sub = _host.Split(subDomSeparator, 2)[1];

            MiWebSiteDomain dominioActual = new MiWebSiteDomain(_sub,ref ConexionDB);
            //HttpContext.Current.Response.Write(dominioActual.id);
            //HttpContext.Current.Response.End();
            if (dominioActual.id != 0)
            {
                GetData(dominioActual);

            }
            else
            {
                dominioActual = new MiWebSiteDomain(_host,ref ConexionDB);
                if (dominioActual.id != 0)
                    GetData(dominioActual);
            }
            ConexionDB.CloseConnection();
            ////HttpContext.Current.Response.Write("Datos de Dominio Cargados");
        }

        private static void GetData(MiWebSiteDomain dominioActual)
        {

            HttpContext.Current.Session["dominio"] = dominioActual.dominio;
            HttpContext.Current.Session["LogotipoDominio"] = dominioActual.logotipo;
            HttpContext.Current.Session["SloganDominio"] = dominioActual.slogan;
            HttpContext.Current.Session["EstadisticasDominio"] = dominioActual.estadisticas;
            HttpContext.Current.Session["KeywordsDominio"] = dominioActual.keywords;
            HttpContext.Current.Session["DescripcionDominio"] = dominioActual.description;
            //HttpContext.Current.Session["idDominio"] = dominioActual.id;
            HttpContext.Current.Session["MapsApiKey"] = dominioActual.mapsApiKey;
            HttpContext.Current.Session["MapPoint"] = dominioActual.mapPoint;
            HttpContext.Current.Session["twitterAccount"] = dominioActual.twitterAccount;
            HttpContext.Current.Session["twitterPassword"] = dominioActual.twitterPassword;
            HttpContext.Current.Session["bitlyApiKey"] = dominioActual.bitlyApiKey;
            HttpContext.Current.Session["idDominio"] = dominioActual.idDomain;
            HttpContext.Current.Session["idParentDomain"] = dominioActual.idParentDomain;
            HttpContext.Current.Session["estadisticas"] = dominioActual.estadisticas;
            HttpContext.Current.Session["idGrandParentDomain"] = dominioActual.idGrandParentDomain;
            HttpContext.Current.Session["ciudad"] = dominioActual.longName;
            HttpContext.Current.Session["TwitterAppId"] = dominioActual.idTwitterApplication;
            HttpContext.Current.Session["oauth_token"] = dominioActual.oauth_token;
            HttpContext.Current.Session["oauth_token_secret"] = dominioActual.oauth_token_secret;
            HttpContext.Current.Session["domainKeywords"] = dominioActual.keywords;

        }

        public static void Refresh()
        {
            GetDeCurrentDomainInfo();
        }

        public static string DomainKeywords
        {
            get
            {
                if (HttpContext.Current.Session["domainKeywords"] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Session["domainKeywords"].ToString();
                //return "";

            }
        }

        public static string estadisticas
        {
            get
            {
                if (HttpContext.Current.Session["estadisticas"] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Session["estadisticas"].ToString();
                //return "";

            }
        }

        public static string MapsApiKey
        {
            get
            {
                if (HttpContext.Current.Session["MapsApiKey"] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Session["MapsApiKey"].ToString();
                //return "";

            }
        }

        public static string MapPoint
        {
            get
            {
                if (HttpContext.Current.Session["MapPoint"] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Session["MapPoint"].ToString();

            }
        }

       

        public static string bitlyApiKey
        {
            get
            {
                if (HttpContext.Current.Session["bitlyApiKey"] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Session["bitlyApiKey"].ToString();

            }
        }

        public static int idParentDomain
        {
            get
            {
                if (HttpContext.Current.Session["idParentDomain"] == null)
                    GetDeCurrentDomainInfo();
                return Convert.ToInt32(HttpContext.Current.Session["idParentDomain"]);

            }
        }

        public static int TwitterAppId
        {
            get
            {
                if (HttpContext.Current.Session["TwitterAppId"] == null)
                    GetDeCurrentDomainInfo();
                return Convert.ToInt32(HttpContext.Current.Session["TwitterAppId"]);

            }
        }

        public static string oauth_token
        {
            get
            {
                if (HttpContext.Current.Session["oauth_token"] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Session["oauth_token"].ToString();

            }
        }

        public static string oauth_token_secret
        {
            get
            {
                if (HttpContext.Current.Session["oauth_token_secret"] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Session["oauth_token_secret"].ToString();

            }
        }



    }


    public struct EmailRecipient
    {
        private string _email;
        private string _name;

        public string Name { get { return _name; } set { _name = value; } }
        public string Email { get { return _email; } set { _email = value; } }
    }

    public struct WebSiteProfile
    {
        private string _website;
        private EmailRecipient _contactEmail;
        private string _smtpUser;
        private string _smtpPassword;
        private string _smtpServer;
        private string _smtpPort;




        //Public Propperties
        public string WebSite { get { return _website; } set { _website = value; } }
        public EmailRecipient ContactEmail { get { return _contactEmail; } set { _contactEmail = value; } }
        public string SMTPUser { get { return _smtpUser; } set { _smtpUser = value; } }
        public string SMTPPassword { get { return _smtpPassword; } set { _smtpPassword = value; } }
        public string SMTPServer { get { return _smtpServer; } set { _smtpServer = value; } }
        public string SMTPPort { get { return _smtpPort; } set { _smtpPort = value; } }
    }


    public class MiWebSiteUser : BaseClass
    {
        #region private fields
        private String _genero;
        private String _nombre;
        private String _apellidos;
        private String _email;
        private String _email2;
        private String _firma;
        private int _direccionDefault;
        private String _telefono;
        private String _fax;
        private String _password;
        private String _username;
        private int _idAvatar;
        private int _idImagen;
        private int _newsletter;
        private DateTime _ultimoLogin;
        private int _NoLogins;
        private int _NoPosts;
        private String _pregunta;
        private String _respuesta;
        private int _ocupacion;
        private int _nivelUsuario;
        private bool _activo;
        private String _openId;
        #endregion

        #region public properties
        public String genero { get { return _genero; } set { _genero = value; } }
        public String nombre { get { return _nombre; } set { _nombre = value; } }
        public String apellidos { get { return _apellidos; } set { _apellidos = value; } }
        public String email { get { return _email; } set { _email = value; } }
        public String email2 { get { return _email2; } set { _email2 = value; } }
        public String firma { get { return _firma; } set { _firma = value; } }
        public int direccionDefault { get { return _direccionDefault; } set { _direccionDefault = value; } }
        public String telefono { get { return _telefono; } set { _telefono = value; } }
        public String fax { get { return _fax; } set { _fax = value; } }
        public String password { get { return _password; } set { _password = value; } }
        public String username { get { return _username; } set { _username = value; } }
        public int idAvatar { get { return _idAvatar; } set { _idAvatar = value; } }
        public int idImagen { get { return _idImagen; } set { _idImagen = value; } }
        public int newsletter { get { return _newsletter; } set { _newsletter = value; } }
        public DateTime ultimoLogin { get { return _ultimoLogin; } set { _ultimoLogin = value; } }
        public int NoLogins { get { return _NoLogins; } set { _NoLogins = value; } }
        public int NoPosts { get { return _NoPosts; } set { _NoPosts = value; } }
        public String pregunta { get { return _pregunta; } set { _pregunta = value; } }
        public String respuesta { get { return _respuesta; } set { _respuesta = value; } }
        public int ocupacion { get { return _ocupacion; } set { _ocupacion = value; } }
        public int nivelUsuario { get { return _nivelUsuario; } set { _nivelUsuario = value; } }
        public bool activo { get { return _activo; } set { _activo = value; } }
        public string OpenID { get { return _openId; } set { _openId = value; } }
        #endregion

        #region constructors
        public MiWebSiteUser(ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            id = classBinder.NewRecord("usuarios");
            string queryString = "";
            queryString = "SELECT * FROM usuarios WHERE id='" + id + "'";
            //HttpContext.Current.Response.Write(queryString);
            //HttpContext.Current.Response.End();
            GetRecord(queryString);
        }

        public MiWebSiteUser(int registryId,ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            string queryString = "";
            queryString = "SELECT * FROM usuarios WHERE id='" + registryId + "'";
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            GetRecord(queryString);
        }

        public MiWebSiteUser(string userName,ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            string queryString = "";
           
                queryString = "SELECT * FROM usuarios WHERE username='" + userName + "' OR email='" + userName + "'";
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            GetRecord(queryString);
        }
        #endregion

        #region public methods



        public void Delete()
        {
            string queryString = "";
            queryString = "DELETE FROM usuarios WHERE id=\"" + id + "\"";
            ConexionDBInterna.ExecuteCommand(queryString);

        }
        #endregion


        #region Private Methods
        private void GetRecord(string queryString)
        {
            OdbcDataReader reader = ConexionDBInterna.ExecuteReader(queryString);
            if (reader.HasRows)
            {
                if (!reader.IsDBNull(reader.GetOrdinal("id")))
                    id = (System.Int32)reader["id"];
                if (!reader.IsDBNull(reader.GetOrdinal("genero")))
                    _genero = (System.String)reader["genero"];
                if (!reader.IsDBNull(reader.GetOrdinal("nombre")))
                    _nombre = (System.String)reader["nombre"];
                if (!reader.IsDBNull(reader.GetOrdinal("apellidos")))
                    _apellidos = (System.String)reader["apellidos"];
                if (!reader.IsDBNull(reader.GetOrdinal("email")))
                    _email = (System.String)reader["email"];
                if (!reader.IsDBNull(reader.GetOrdinal("email2")))
                    _email2 = (System.String)reader["email2"];
                if (!reader.IsDBNull(reader.GetOrdinal("firma")))
                    _firma = (System.String)reader["firma"];
                if (!reader.IsDBNull(reader.GetOrdinal("direccionDefault")))
                    _direccionDefault = (System.Int32)reader["direccionDefault"];
                if (!reader.IsDBNull(reader.GetOrdinal("telefono")))
                    _telefono = (System.String)reader["telefono"];
                if (!reader.IsDBNull(reader.GetOrdinal("fax")))
                    _fax = (System.String)reader["fax"];
                if (!reader.IsDBNull(reader.GetOrdinal("password")))
                    _password = (System.String)reader["password"];
                if (!reader.IsDBNull(reader.GetOrdinal("username")))
                    _username = (System.String)reader["username"];
                if (!reader.IsDBNull(reader.GetOrdinal("idAvatar")))
                    _idAvatar = (System.Int32)reader["idAvatar"];
                if (!reader.IsDBNull(reader.GetOrdinal("idImagen")))
                    _idImagen = (System.Int32)reader["idImagen"];
                //if (!reader.IsDBNull(reader.GetOrdinal("newsletter")))
                //    _newsletter = (System.Int32)reader["newsletter"];
                if (!reader.IsDBNull(reader.GetOrdinal("fechaCreacion")))
                    fechaCreacion = Convert.ToDateTime(reader["fechaCreacion"]); if (!reader.IsDBNull(reader.GetOrdinal("fechaModificacion"))) fechaModificacion = Convert.ToDateTime(reader["fechaModificacion"]); if (!reader.IsDBNull(reader.GetOrdinal("idUsuarioModificacion"))) idUsuarioModificacion = (System.Int32)reader["idUsuarioModificacion"];


                if (!reader.IsDBNull(reader.GetOrdinal("ultimoLogin")))
                    _ultimoLogin = Convert.ToDateTime(reader["ultimoLogin"]);
                if (!reader.IsDBNull(reader.GetOrdinal("NoLogins")))
                    _NoLogins = (System.Int32)reader["NoLogins"];
                if (!reader.IsDBNull(reader.GetOrdinal("NoPosts")))
                    _NoPosts = (System.Int32)reader["NoPosts"];
                if (!reader.IsDBNull(reader.GetOrdinal("pregunta")))
                    _pregunta = (System.String)reader["pregunta"];
                if (!reader.IsDBNull(reader.GetOrdinal("respuesta")))
                    _respuesta = (System.String)reader["respuesta"];
                if (!reader.IsDBNull(reader.GetOrdinal("ocupacion")))
                    _ocupacion = (System.Int32)reader["ocupacion"];
                if (!reader.IsDBNull(reader.GetOrdinal("nivelUsuario")))
                    _nivelUsuario = (System.Int32)reader["nivelUsuario"];
                if (!reader.IsDBNull(reader.GetOrdinal("activo")))
                    _activo = Convert.ToBoolean(reader["activo"]);
                if (!reader.IsDBNull(reader.GetOrdinal("openId")))
                    _openId = (System.String)reader["openId"];
            }
        }


        protected override void UpdateBind()
        {
            StringBuilder strCommand = new StringBuilder();
            strCommand.Append("UPDATE usuarios set "); 
            if(ConexionDBInterna.DBType!=2)
                strCommand.Append("fechaModificacion='" + this.fechaModificacion.ToString("yyyy-MM-dd HH:mm:ss") + "'"); 
            else
                strCommand.Append("fechaModificacion=CONVERT(datetime,'" + this.fechaModificacion.ToString("yyyy-MM-dd HH:mm:ss") + "')"); 
            strCommand.Append(",idUsuarioModificacion='" + idUsuarioModificacion.ToString() + "'");
            //strCommand.Append("genero=\"" + this._genero.ToString() + "\"");
            strCommand.Append(",nombre='" + this._nombre.ToString() + "'");
            strCommand.Append(",apellidos='" + this._apellidos.ToString() + "'");
            strCommand.Append(",email='" + this._email.ToString() + "'");
            //strCommand.Append(",email2=\"" + this._email2.ToString() + "\"");
            //strCommand.Append(",firma=\"" + this._firma.ToString() + "\"");
            //strCommand.Append(",direccionDefault=\"" + this._direccionDefault.ToString() + "\"");
            strCommand.Append(",telefono='" + this._telefono.ToString() + "'");
            strCommand.Append(",fax='" + this._fax.ToString() + "'");
            strCommand.Append(",password='" + this._password.ToString() + "'");
            strCommand.Append(",username='" + this._username.ToString() + "'");
            //strCommand.Append(",idAvatar=\"" + this._idAvatar.ToString() + "\"");
            //strCommand.Append(",idImagen=\"" + this._idImagen.ToString() + "\"");
            //strCommand.Append(",newsletter=\"" + this._newsletter.ToString() + "\"");
            //if(ConexionDB.DBType!=2)
            //strCommand.Append(",ultimoLogin='" + this._ultimoLogin.ToString("yyyy-MM-dd HH:mm:ss") + "'");
            //strCommand.Append(",NoLogins=\"" + this._NoLogins.ToString() + "\"");
            //strCommand.Append(",NoPosts=\"" + this._NoPosts.ToString() + "\"");
            //strCommand.Append(",pregunta=\"" + this._pregunta.ToString() + "\"");
            //strCommand.Append(",respuesta=\"" + this._respuesta.ToString() + "\"");
            //strCommand.Append(",ocupacion=\"" + this._ocupacion.ToString() + "\"");
            strCommand.Append(",nivelUsuario=" + this._nivelUsuario.ToString() + "");
            //if(ConexionDB.DBType==2)
                strCommand.Append(",activo=" + Convert.ToInt16(this._activo) + "");
            //else
            //    strCommand.Append(",activo='" + this._activo.ToString() + "'");
            strCommand.Append(",openID='" + this._openId.ToString() + "'");

            strCommand.Append(" WHERE id='" + id + "'");
            ConexionDBInterna.ExecuteCommand(strCommand.ToString());
        }
        #endregion

    }

    public class LogedUserData
    {
        #region private fields
        private int _id;
        private string _userName;
        private string _userEmail;
        private string _password;
        private DateTime _LastLogin;
        private int _userLevel;
        private string _userFullName;
        #endregion

        #region public properties
        public int UserId { get { return _id; } }
        public string UserName { get { return _userName; } }
        public string Email { get { return _userEmail; } }
        public DateTime LastLogin { get { return _LastLogin; } }
        public int UserLevel { get { return _userLevel; } }
        public string FullName { get { return _userFullName; } }
        public string Password { get { return _password; } }
        #endregion

        #region constructors
        public LogedUserData()
        {
            if (HttpContext.Current.Session["password"] != null)
            {
                _password = Convert.ToString(HttpContext.Current.Session["password"]);
                _id = Convert.ToInt32(HttpContext.Current.Session["idUsuario"]);
                _userEmail = Convert.ToString(HttpContext.Current.Session["email"]);
                _userLevel = Convert.ToInt32(HttpContext.Current.Session["nivelUsuario"]);
                _userName = Convert.ToString(HttpContext.Current.Session["UserName"]);
                _LastLogin = Convert.ToDateTime(HttpContext.Current.Session["LastLogin"]);
                _userFullName = Convert.ToString(HttpContext.Current.Session["FullName"]);
            }
            else
                _userLevel = 1;
        }
        #endregion
    }

    public class UsersCollection
    {
        private dbConnector ConexionDB;
        private BaseClassArray<MiWebSiteUser> _items;

        public BaseClassArray<MiWebSiteUser> UsersList { get { return _items; } }
        public UsersCollection()
        {

        }

        public UsersCollection(bool loadClientData,ref dbConnector ConexionDB)
        {
            
            string strCommand = "SELECT id FROM usuarios order by id desc";

            OdbcDataReader clientReader = ConexionDB.ExecuteReader(strCommand);
            _items = new BaseClassArray<MiWebSiteUser>();
            while (clientReader.Read())
            {
                MiWebSiteUser newUser = new MiWebSiteUser(Convert.ToInt32(clientReader["id"]),ref ConexionDB);

                _items.Add(newUser);
            }
            clientReader.Close();
            clientReader.Dispose();
        }

    }

    public class UsuarioDireccion : BaseClass
    {
        #region private fields
        private int _idUsuarioDireccion;
        private String _empresa;
        private String _nombre;
        private String _apellidos;
        private String _calle;
        private String _colonia;
        private String _CP;
        private String _Ciudad;
        private String _estado;
        private String _pais;
        #endregion

        #region public properties
        public int idUsuarioDireccion { get { return _idUsuarioDireccion; } set { _idUsuarioDireccion = value; } }
        public String empresa { get { return _empresa; } set { _empresa = value; } }
        public String nombre { get { return _nombre; } set { _nombre = value; } }
        public String apellidos { get { return _apellidos; } set { _apellidos = value; } }
        public String calle { get { return _calle; } set { _calle = value; } }
        public String colonia { get { return _colonia; } set { _colonia = value; } }
        public String CP { get { return _CP; } set { _CP = value; } }
        public String Ciudad { get { return _Ciudad; } set { _Ciudad = value; } }
        public String estado { get { return _estado; } set { _estado = value; } }
        public String pais { get { return _pais; } set { _pais = value; } }
        #endregion

        #region constructors
        public UsuarioDireccion(ref dbConnector ConexionDB)
        {
            
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            id = classBinder.NewRecord("USUARIOSDIRECCIONES");
            string queryString = "";
            queryString = "SELECT * FROM USUARIOSDIRECCIONES WHERE id=\"" + id + "\"";
            GetRecord(queryString);
        }

        public UsuarioDireccion(int registryId,ref dbConnector ConexionDB)
        {
            
            string queryString = "";
            queryString = "SELECT * FROM USUARIOSDIRECCIONES WHERE id='" + registryId + "'";
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            this.GetRecord(queryString);
        }
        #endregion

        #region public methods

        public void Delete()
        {
            string queryString = "";
            queryString = "DELETE FROM USUARIOSDIRECCIONES WHERE id=\"" + id + "\"";
            ConexionDBInterna.ExecuteCommand(queryString);

        }
        #endregion

        #region Private Methods
        private void GetRecord(string queryString)
        {
            OdbcDataReader reader = ConexionDBInterna.ExecuteReader(queryString);
            if (reader.HasRows)
            {
                if (!reader.IsDBNull(reader.GetOrdinal("id")))
                    id = (System.Int32)reader["id"];
                if (!reader.IsDBNull(reader.GetOrdinal("fechaCreacion")))
                    fechaCreacion = Convert.ToDateTime(reader["fechaCreacion"]); if (!reader.IsDBNull(reader.GetOrdinal("fechaModificacion"))) fechaModificacion = Convert.ToDateTime(reader["fechaModificacion"]); if (!reader.IsDBNull(reader.GetOrdinal("idUsuarioModificacion"))) idUsuarioModificacion = (System.Int32)reader["idUsuarioModificacion"];


                if (!reader.IsDBNull(reader.GetOrdinal("idUsuario")))
                    idUsuario = (System.Int32)reader["idUsuario"];
                if (!reader.IsDBNull(reader.GetOrdinal("idUsuarioDireccion")))
                    _idUsuarioDireccion = (System.Int32)reader["idUsuarioDireccion"];
                if (!reader.IsDBNull(reader.GetOrdinal("empresa")))
                    _empresa = (System.String)reader["empresa"];
                if (!reader.IsDBNull(reader.GetOrdinal("nombre")))
                    _nombre = (System.String)reader["nombre"];
                if (!reader.IsDBNull(reader.GetOrdinal("apellidos")))
                    _apellidos = (System.String)reader["apellidos"];
                if (!reader.IsDBNull(reader.GetOrdinal("calle")))
                    _calle = (System.String)reader["calle"];
                if (!reader.IsDBNull(reader.GetOrdinal("colonia")))
                    _colonia = (System.String)reader["colonia"];
                if (!reader.IsDBNull(reader.GetOrdinal("CP")))
                    _CP = (System.String)reader["CP"];
                if (!reader.IsDBNull(reader.GetOrdinal("Ciudad")))
                    _Ciudad = (System.String)reader["Ciudad"];
                if (!reader.IsDBNull(reader.GetOrdinal("estado")))
                    _estado = (System.String)reader["estado"];
                if (!reader.IsDBNull(reader.GetOrdinal("pais")))
                    _pais = (System.String)reader["pais"];
            }
        }

        protected override void UpdateBind()
        {
            StringBuilder strCommand = new StringBuilder();
            strCommand.Append("UPDATE USUARIOSDIRECCIONES set "); strCommand.Append("fechaModificacion='" + this.fechaModificacion.ToString("yyyy-MM-dd HH:mm:ss") + "'"); strCommand.Append(",idUsuarioModificacion=\"" + idUsuarioModificacion.ToString() + "\"");

            strCommand.Append(",idUsuarioDireccion=\"" + this._idUsuarioDireccion.ToString() + "\"");
            strCommand.Append(",empresa=\"" + this._empresa.ToString() + "\"");
            strCommand.Append(",nombre=\"" + this._nombre.ToString() + "\"");
            strCommand.Append(",apellidos=\"" + this._apellidos.ToString() + "\"");
            strCommand.Append(",calle=\"" + this._calle.ToString() + "\"");
            strCommand.Append(",colonia=\"" + this._colonia.ToString() + "\"");
            strCommand.Append(",CP=\"" + this._CP.ToString() + "\"");
            strCommand.Append(",Ciudad=\"" + this._Ciudad.ToString() + "\"");
            strCommand.Append(",estado=\"" + this._estado.ToString() + "\"");
            strCommand.Append(",pais=\"" + this._pais.ToString() + "\"");
            strCommand.Append(" WHERE id=\"" + id + "\"");
            ConexionDBInterna.ExecuteCommand(strCommand.ToString());
        }
        #endregion
    }

    public class UsuarioDireccionCollection
    {
        private dbConnector ConexionDB;
        private BaseClassArray<UsuarioDireccion> _items;

        public BaseClassArray<UsuarioDireccion> Elementos { get { return _items; } }
        public UsuarioDireccionCollection()
        {

        }

        public UsuarioDireccionCollection(int idUsuario,ref dbConnector ConexionDB)
        {
            
            string strCommand = "SELECT id FROM USUARIOSDIRECCIONES WHERE idUsuarioDireccion='" + idUsuario + "' ORDER by id desc";

            OdbcDataReader dataReader = ConexionDB.ExecuteReader(strCommand);
            _items = new BaseClassArray<UsuarioDireccion>();
            while (dataReader.Read())
            {
                UsuarioDireccion newItem = new UsuarioDireccion(Convert.ToInt32(dataReader["id"]),ref ConexionDB);

                _items.Add(newItem);
            }
            dataReader.Close();
            dataReader.Dispose();
        }

    }

}
